import java.util.Random;

public class test2 {
    public int findKthLargest(int[] nums, int k) {
        int ret = qsort(nums, k, 0, nums.length-1);
        return ret;
    }

    public int qsort(int[] nums, int k, int l, int r) {
        if (l == r) {
            return nums[l];
        }
        int key = nums[new Random().nextInt(r - l + 1) + l];

        int left = l - 1, right = r + 1, i = l;
        while (i < right) {
            if (nums[i] < key) {
                swap(nums, ++left, i++);
            } else if (nums[i] == key) {
                i++;
            } else {
                swap(nums, --right, i);
            }
        }
        int c = r - right + 1;
        int b = right - 1 - left - 1 + 1;
        int a = left - l + 1;


        if (c >= k) {
            return qsort(nums, k, right, r);
        } else if (b + c >= k) {
            return key;
        } else {
            return qsort(nums, k - b - c, l, left);
        }
    }

    public void swap(int[] nums, int a, int b) {
        int temp = nums[a];
        nums[a] = nums[b];
        nums[b] = temp;
    }
}
